#!/usr/bin/env bash
TRAIN_VECTORS=$1
TRAIN_ANSWERS=$2
SPLITTING=$3

JOINED="$TRAIN_VECTORS.joined"
paste -d ' ' "$TRAIN_VECTORS" "$TRAIN_ANSWERS" > "$JOINED"
RANDOMED="$JOINED.randomed"
sort -R "$JOINED" > "$RANDOMED"
rm -rf "$JOINED"
SPLITTED_PREFIX="$RANDOMED.splitted"
LINE_COUNT=`cat "$RANDOMED" | wc -l`
CHUNK_SIZE=`echo "$LINE_COUNT"/"$SPLITTING" | bc`
split  -l "$CHUNK_SIZE" "$RANDOMED" "$SPLITTED_PREFIX"
rm -rf "$RANDOMED"
SPLITTED=`ls -1 "$SPLITTED_PREFIX"*`

COUNTER=0
DATA_DIR=`dirname "$TRAIN_VECTORS"`
rm -rf $DATA_DIR/[0-9]*
while [[ "$COUNTER" -lt "$SPLITTING" ]];
do
    TARGET_DIR=$DATA_DIR/$COUNTER
    rm -rf "$TARGET_DIR"
    mkdir -p "$TARGET_DIR"

    TRAIN_FILE=$TARGET_DIR/train.txt
    TEST_FILE=$TARGET_DIR/test.txt
    TRAIN_ANSWERS_FILE=$TRAIN_FILE.answers
    TEST_ANSWERS_FILE=$TEST_FILE.answers
    TRAIN_JOINED_FILE=$TRAIN_FILE.joined
    TEST_JOINED_FILE=$TEST_FILE.joined

    rm -rf "$TRAIN_FILE" "$TEST_FILE"

    PART_NUM=0
    for PART in $SPLITTED;
    do
        if [[ "$PART_NUM" == "$COUNTER" ]];
        then
            cat "$PART" > "$TEST_JOINED_FILE"
        else
            cat "$PART" >> "$TRAIN_JOINED_FILE"
        fi

        PART_NUM=$((PART_NUM + 1))
    done

    cut -d ' ' -f 1,2,3,4,5 "$TRAIN_JOINED_FILE" > "$TRAIN_FILE"
    cut -d ' ' -f 6 "$TRAIN_JOINED_FILE" > "$TRAIN_ANSWERS_FILE"

    cut -d ' ' -f 1,2,3,4,5 "$TEST_JOINED_FILE" > "$TEST_FILE"
    cut -d ' ' -f 6 "$TEST_JOINED_FILE" > "$TEST_ANSWERS_FILE"

    rm -rf "$TRAIN_JOINED_FILE" "$TEST_JOINED_FILE"

    COUNTER=$((COUNTER + 1))
done

rm -rf "$SPLITTED_PREFIX"*
